<template>
  <div class="mpd-workspace-page-widget">
    <div class="show-box selected" :style="selectedStyle" v-if="currentItem.id">
      <div class="title bg-color-blue text-color-white">{{ currentItem.title }}</div>
      <div class="toolbar bg-color-blue">
        <mpd-tooltip v-if="showDeleteBtn" placement="top" title="删除">
          <a-popconfirm title="确定删除？" ok-text="确定" cancel-text="取消" @confirm="confirmDeleteHandle">
            <mpd-icon icon="mpd-icon-shanchu"></mpd-icon>
          </a-popconfirm>
        </mpd-tooltip>
        <a-dropdown placement="bottomRight">
          <mpd-icon icon="mpd-icon-gengduo"></mpd-icon>
          <a-menu slot="overlay" @click="moreMenuClick">
            <a-menu-item key="cancelSelect">取消选中</a-menu-item>
          </a-menu>
        </a-dropdown>
      </div>
    </div>
  </div>
</template>

<script>
import _ from 'lodash'
import { deleteItem, selectItem } from '@/util/pageUtil'

export default {
  props: {
    // 点击选中item的key
    selectItemKey: {
      type: String,
      default() {
        return 'item'
      }
    }
  },
  inject: ['mpdPageConfig', 'selectPageNodeDom'],
  data() {
    return {
      selectedStyle: {
        top: 0,
        left: 0,
        width: 0,
        height: 0
      },
      // 创建观察器,创建一个观察器实例并传入回调函数
      resizeObserver: null,
      mutationObserver: null
    }
  },
  computed: {
    currentItem() {
      return this.selectPageNodeDom[this.selectItemKey]
    },
    showDeleteBtn() {
      if (this.selectItemKey === 'item') {
        return this.mpdPageConfig.id !== this.currentItem.id
      } else {
        if (this.selectPageNodeDom.item.mpdConfig.slot && this.selectPageNodeDom.item.mpdConfig.slot.length > 0) {
          return !this.selectPageNodeDom.item.mpdConfig.slot.some(
            (item) => item.id === this.selectPageNodeDom.slotItem.id
          )
        }
      }
      return true
    }
  },
  watch: {
    'selectPageNodeDom.item.id': {
      handler: function (val) {
        this.$nextTick(() => {
          this.addListener(val, 'item')
          this.modifyShowBox(val, 'item')
        })
      }
    },
    'selectPageNodeDom.slotItem.id': {
      handler: function (val) {
        this.$nextTick(() => {
          this.addListener(val, 'slotItem')
          this.modifyShowBox(val, 'slotItem')
        })
      }
    }
  },
  methods: {
    // 修改展示的dom位置
    modifyShowBox(id, key) {
      if (this.selectItemKey === key && id) {
        const parentCanvas = this.$el.offsetParent
        const $target = parentCanvas.querySelector(`[id='${id}']`)
        if ($target) {
          const canvasRect = parentCanvas.getBoundingClientRect()
          const targetRect = $target.getBoundingClientRect()
          this.selectedStyle.top = targetRect.top - canvasRect.top + parentCanvas.scrollTop + 'px'
          this.selectedStyle.left = targetRect.left - canvasRect.left + 'px'
          this.selectedStyle.width = targetRect.width + 'px'
          this.selectedStyle.height = targetRect.height + 'px'
          // } else if (this.selectItemKey === 'slotItem') {
          //   selectItem(this.selectPageNodeDom, this.selectPageNodeDom.item)
          // } else {
          //   selectItem(this.selectPageNodeDom)
        }
      }
    },
    // 删除选中对象
    confirmDeleteHandle() {
      deleteItem(this.selectPageNodeDom[this.selectItemKey], this.mpdPageConfig.children)
      if (this.selectItemKey === 'item') {
        selectItem(this.selectPageNodeDom)
      } else {
        selectItem(this.selectPageNodeDom, this.selectPageNodeDom.item)
      }
    },
    // 更多菜单点击事件
    moreMenuClick(obj) {
      switch (obj.key) {
        case 'cancelSelect':
          selectItem(this.selectPageNodeDom)
          break
      }
    },
    // 监听选中节点变化
    addListener(id, key) {
      this.disconnectListener()
      if (id) {
        this.resizeObserver = new ResizeObserver(() => this.modifyShowBox(id, key))
        this.mutationObserver = new MutationObserver(() => this.modifyShowBox(id, key))
        this.$nextTick(() => {
          // 观察器的配置（需要观察什么变动）
          // 以上述配置开始观察目标节点
          const $rootDom = document.getElementById(id)
          if ($rootDom) {
            // 监听视图大小变化
            this.resizeObserver.observe($rootDom)
            // 配置开始观察目标节点
            this.mutationObserver.observe($rootDom, {
              attributes: true,
              childList: true,
              characterData: true,
              subtree: true
            })
          } else {
            console.error(`节点dom没有获取到：${id}`)
          }
        })
      }
    },
    // 销毁监听，停止观察
    disconnectListener() {
      if (this.resizeObserver) {
        this.resizeObserver.disconnect()
      }
      if (this.mutationObserver) {
        this.mutationObserver.disconnect()
      }
    }
  },
  destroyed() {
    this.disconnectListener()
  }
}
</script>

<style lang="less">
.mpd-workspace-page-widget {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 100;
  pointer-events: none;
  .show-box {
    position: absolute;
    background-color: rgba(66, 133, 244, 0.1);
    outline: 1px solid #4285f4;
    // 组件标题
    .title {
      top: -18px;
      left: -1px;
      position: absolute;
      font-size: 12px;
      padding: 0 5px;
      white-space: nowrap;
    }
    // 工具栏
    .toolbar {
      top: -18px;
      right: -1px;
      position: absolute;
      line-height: 18px;
      pointer-events: all;
      .mpd-icon {
        font-size: 12px;
        cursor: pointer;
        margin: 0 2px;
        color: #eeeeee;
        &:hover {
          color: #ffffff;
        }
      }
    }
  }
}
</style>
